<template>
  <div>XLSX</div>
  <a-table :columns="columns" :dataSource="sourceData"></a-table>
  <button @click="exportExcel">下载</button>
</template>

<script lang="ts">
import * as XLSX from 'xlsx'
import * as XLSXS from 'xlsx-style'
import * as FileSaver from 'file-saver'
export default {
  // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  setup () {
    interface sourceDataDefine {
      cardNumber: string;
      cardName: string;
      type: string;
      transactionAmount: number;
      merchantName: string;
      status: string;
      Date: string;
    }
    var sourceData:sourceDataDefine[] = [
      {
        cardNumber: '2012',
        cardName: '实体卡',
        type: 'Completed',
        transactionAmount: 120,
        merchantName: 'aa',
        status: 'status',
        Date: '2020-10-10'
      }, {
        cardNumber: '2055',
        cardName: '虚拟',
        type: 'Completed',
        transactionAmount: 120,
        merchantName: 'aa',
        status: 'status',
        Date: '2020-10-10'
      }
    ]
    const columns = [{
      title: 'Card Number',
      dataIndex: 'cardNumber'
    }, {
      title: 'Name',
      dataIndex: 'cardName'
    }, {
      title: 'Type',
      dataIndex: 'type'
    }, {
      title: 'Amount',
      dataIndex: 'transactionAmount'
    }, {
      title: 'Description',
      dataIndex: 'merchantName'
    }, {
      title: 'Status',
      dataIndex: 'status'
    }, {
      title: 'Date',
      dataIndex: 'Date'
    }]
    // 导出
    const exportExcel = async () => {
      const multiHeader:string[] = ['http://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/img/vip-entry.a14de9c.png', '', '', '', '', '', '']
      const multiblankLine = 2

      const sheetFilter:string[] = ['cardNumber', 'cardName', 'type', 'transactionAmount', 'merchantName', 'status', 'Date']
      const sheetHeader:string[] = ['Card Number', 'Name', 'Type', 'Amount', 'Description', 'Status', 'Date']
      const footerData:string[] = ['XXXX', '广州市天河区XXX街道XXX号', 'Tel: 202-10086; Fax:020-10086', 'Email: 123456@qq.com', 'Website: www.juejin.cn']
      let sheetData:any = []
      sheetData = changeData(sourceData, sheetFilter)
      if (sheetHeader) {
        sheetData.unshift(sheetHeader)
      }
      const mergesArr = []
      // 设置标题行单元格合并
      // s即start, e即end, r即row, c即column
      // 合并从--0行0列开始,到0行3列
      if (multiHeader.length > 0) {
        mergesArr.push({ s: { r: 0, c: 0 }, e: { r: 2, c: (multiHeader.length - 1) } })
        if (multiblankLine > 0) {
          for (let i = 0; i < multiblankLine; i++) {
            const newArr = []
            for (let j = 0; j < sheetHeader.length; j++) {
              newArr.push('')
            }
            sheetData.unshift(newArr)
          }
        }
        sheetData.unshift(multiHeader)
      }
      if (footerData.length > 0) {
        // mergesArr.push({ s: { r: 0, c: 0 }, e: { r: 2, c: multiHeader.length }})
        const height = sheetData.length
        for (let i = 0; i < footerData.length; i++) {
          const arr:any = []
          for (let j = 0; j < sheetHeader.length; j++) {
            if (j === 0) {
              arr.push(footerData[i])
            } else {
              arr.push('')
            }
          }
          console.log(height + i)
          mergesArr.push({ s: { r: height + i, c: 0 }, e: { r: height + i, c: (multiHeader.length - 1) } })
          sheetData.push(arr)
        }
      }
      // // 导出的excel文件名
      const filename = 'bill.xlsx'

      // Excel第一个sheet的名称
      // eslint-disable-next-line camelcase
      const ws_name = 'Sheet1'
      const wb = XLSX.utils.book_new()
      const ws = XLSX.utils.aoa_to_sheet(sheetData)
      XLSX.utils.book_append_sheet(wb, ws, ws_name) // 将数据添加到工作薄

      ws['!merges'] = mergesArr
      ws.A1.s = {
        alignment: {
          horizontal: 'center',
          vertical: 'center'
        }
      }

      // 导出Excel, 注意这里用到的是XLSXS对象
      const wbout = XLSXS.write(wb, { bookType: 'xlsx', bookSST: false, type: 'binary' })
      // FileSaver.saveAs( new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), filename)
      try {
        FileSaver.saveAs(
          new Blob([s2ab(wbout)], { type: 'application/octet-stream' }),
          filename
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }

      await getUrlBase64('http://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/img/vip-entry.a14de9c.png', 'png').then(res => {
        console.log(res)
      // var workbook = XLSX.utils.book_new()
      // workbook.SheetNames[0] = 'sheet名'
      // workbook.Sheets['sheet名'] = {}
      // var ws2 = workbook.Sheets[workbook.SheetNames[0]]
      // ws2['!images'] = [
      //   {
      //     name: 'image1.jpg',
      //     data: res,
      //     opts: { base64: true },
      //     position: {
      //       type: 'twoCellAnchor',
      //       attrs: { editAs: 'oneCell' },
      //       to: { col: 20, row: 46 }
      //     }
      //   }
      // ]
      // const copyData = ['Card Number', 'Name', 'Type', 'Amount', 'Description', 'Status', 'Date']
      // XLSX.utils.sheet_add_json(ws2, copyData, { origin: 'A51' })
      // XLSX.writeFile(workbook, 'hinsyu.xlsx')
      })
      // html2canvas($('#charts')[0]).then(function (canvas) {

      // })
      /**
       * 工具方法
       */
      function s2ab (s:any) {
        var buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
        return buf
      }
      function changeData (data:any, filter:any) {
        const sj = data
        const f = filter
        let re = []
        Array.isArray(data) ? (function () {
          // 对象
          f ? (function () {
            // 存在过滤
            sj.forEach(function (obj:any) {
              const one:any = []
              filter.forEach(function (no:any) {
                one.push(obj[no])
              })
              re.push(one)
            })
          })()
            : (function () {
              // 不存在过滤
              sj.forEach(function (obj:any) {
                const col = Object.keys(obj)
                const one:any = []
                col.forEach(function (no) {
                  one.push(obj[no])
                })
                re.push(one)
              })
            })()
        })()
          : (function () {
            re = sj
          })()
        return re
      }
      function getUrlBase64 (url:string, ext:string) {
        return new Promise((resolve) => {
          let canvas:any = document.createElement('canvas') // 创建canvas DOM元素
          const ctx:any = canvas.getContext('2d')
          const img = new Image()
          img.crossOrigin = 'Anonymous'
          img.src = url
          img.onload = function () {
            canvas.height = img.height // 指定画板的高度,自定义
            canvas.width = img.width // 指定画板的宽度，自定义
            ctx.drawImage(img, 0, 0, img.width, img.height) // 参数可自定义
            const dataURL = canvas.toDataURL('image/' + ext)
            canvas = null
            resolve(dataURL) // Base64编码
          }
        })
      }
    }
    return {
      columns,
      sourceData,
      exportExcel
    }
  }
}
</script>

<style>
</style>
